/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    //先序
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr||root==p||root==q)return root;//找到结点返回或者返回空

        TreeNode* left=lowestCommonAncestor(root->left,p,q);//递归左子树
        TreeNode* right=lowestCommonAncestor(root->right,p,q);//递归右子树

        if(left==nullptr&&right==nullptr)return nullptr;//左子树和右子树都没找到，则不存在目标节点在树中
        if(left==nullptr)return right;//如果左子树没找到目标结点，那么都在右子树
        if(right==nullptr)return left;//如果右子树没找到目标结点，那么都在左子树
        return root;//左子树右子树都找到目标结点，在异侧，当前root即为最近公共祖先

    }
};